const fs = require('fs');

const manifestPath = process.env.UNI_INPUT_DIR + '/manifest.json';
let Manifest = fs.readFileSync(manifestPath, {
  encoding: 'utf-8',
});

function replaceManifest(path, value) {
  const arr = path.split('.');
  const len = arr.length;
  const lastItem = arr[len - 1];

  let i = 0;
  let ManifestArr = Manifest.split(/\n/);

  for (let index = 0; index < ManifestArr.length; index++) {
    const item = ManifestArr[index];
    if (new RegExp(`"${arr[i]}"`).test(item)) ++i;
    if (i === len) {
      const hasComma = /,/.test(item);
      ManifestArr[index] = item.replace(
        new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`),
        `"${lastItem}": ${value}${hasComma ? ',' : ''}`
      );
      break;
    }
  }

  Manifest = ManifestArr.join('\n');
}
//console.log(process.env.VUE_APP_PATH);
// 动态配置
if (process.env.VUE_APP_PATH == '/') {
  replaceManifest('h5.router.base', `"` + process.env.VUE_APP_PATH + `"`);
  replaceManifest('h5.router.publicPath', `"` + process.env.VUE_APP_PATH + `"`);
  //replaceManifest('name', `"` + process.env.VUE_APP_TITlE + `"`);
} else {
  replaceManifest('h5.router.base', `"` + process.env.VUE_APP_PATH + `"`);
  replaceManifest('h5.router.publicPath', `"` + process.env.VUE_APP_PATH + `"`);
  //replaceManifest('name', `"` + process.env.VUE_APP_TITlE + `"`);
}

fs.writeFileSync(manifestPath, Manifest, {
  flag: 'w',
});
